setwd("~/Dropbox/research/accommodation/replicationfiles")

library(tidyverse)
library(haven)
library(ggwaffle)
library(readxl)
library(lubridate)
library(nnet)
library(ggstance)
library(interflex)
library(texreg)

# Load main data ----

acdf <- read_rds("accommodation-repdata.rds")

# Load helper functions ----

source("helperfunctions.r")

# A Social Democratic governments ----

sdcabs <- read_dta("socdemcabinets.dta") %>% 
  mutate(cabtype=case_when(leftwing==0 & rightwing==0 ~ "Single party govt.",
                           leftwing==1 & rightwing==0 ~ "Left wing partner(s)",
                           leftwing==0 & rightwing==1 ~ "Right wing partner(s)",
                           leftwing==1 & rightwing==1 ~ "Left and right wing partners"))

wsdcabs <- waffle_iron(sdcabs,aes_d(group=cabtype),rows=12)

ggplot(wsdcabs,aes(x,y,fill=group)) +
  geom_waffle() +
  coord_equal() + 
  scale_fill_manual(values = c("black","gray25","gray50","gray80")) +
  theme_waffle() +
  theme(legend.title = element_blank()) +
  scale_x_continuous(name = "") +
  scale_y_continuous(name = "") +
  ggtitle("Social Democratic-led governments\nby cabinet composition")

ggsave("figa1.pdf")

# B Media coverage -----

cont <- read_xlsx("govtcoverage.xlsx")

#filter out media stories from after data collection has ended
cont2 <- cont %>% 
  filter(dato<dmy("18-06-2019")) 

# Article content

topicdf <- cont2 %>% 
  mutate(id=1:nrow(cont2)) %>% 
  select(id,starts_with("emne")) %>% 
  summarise(clim=mean(emne_klima),
            econ=mean(emne_økonomi),
            immi=mean(emne_indvandrere)) %>% 
  gather() %>% 
  mutate(topicfac=fct_reorder(factor(c("Climate change","Economy","Immigration")),-value),
         pct=value*100)

ggplot(topicdf,aes(x=topicfac,y=pct)) +
  geom_col() +
  theme_bw() +
  labs(x="",y="Share of articles mentioning topic (pct.)")

ggsave("figb1.pdf")

# Framing of SD position

immframedf <- tibble(code=cont2$S_indvandrere) %>% 
  filter(code>0)

immframeproptable <- immframedf$code %>% table() %>% prop.table()

wpreds <- waffle_iron(tibble(pred=c(rep("No concessions",round(immframeproptable[1]*100)),
                                    rep("Concessions",round(immframeproptable[2]*100)),
                                    rep("No prediction",round(immframeproptable[3]*100)))),aes_d(group=pred),
                      rows=10)

ggplot(wpreds,aes(x,y,fill=group)) +
  geom_waffle() +
  coord_equal() + 
  scale_fill_manual(values = c("gray10","gray50","gray80")) +
  theme_waffle() +
  theme(legend.title = element_blank()) +
  scale_x_continuous(name = "") +
  scale_y_continuous(name = "") +
  ggtitle("Media predictions about Social Democrats'\nimmigration policy concessions (pct.)")

ggsave("figb2.pdf")

# D Balance checks ----

pretreatvarsdf <- tibble(fctvar=c("partygroup15","gender","agegrp","region","occupation","education","hhincome"),
                         fctvarlab=c("Prior election party group vote choice",
                                     "Gender",
                                     "Age group",
                                     "Region",
                                     "Occupation",
                                     "Education",
                                     "Household income"))

levels(acdf$gender) <- c("Female","Male")
levels(acdf$agegrp) <- c("18-34","35-54","55+")
levels(acdf$education) <- c("Middle school","High school","Vocational high school",
                            "Other vocational","Short tertiary","Medium tertiary","Long tertiary",
                            "Ph.D","Prefer not to say")
levels(acdf$hhincome) <- c("<100k","100k-199k","200k-299k","300k-399k","400k-499k",
                           "500k-599k","600k-699k","700k-799k","800k-899k","900k-999k",
                           "1M+","Prefer not to say","DK")
levels(acdf$occupation) <- c("Retired","Unemployed","Stay-at-home","Student","Employee",
                             "Manual worker","Business owner","Other")
levels(acdf$region) <- c("Capital","Zealand","Southern","Mid-Jutland","Northern Jutland")


balanceplotdf <- pmap_dfr(pretreatvarsdf,getbalancetests)

ggplot(balanceplotdf,aes(x=estimate,y=varlab,color=y.level)) +
  geom_point(position = position_dodgev(height=.3)) +
  geom_errorbarh(aes(xmin=estimate-2*std.error,xmax=estimate+2*std.error),height=0,
                 position = position_dodgev(height=.3)) +
  geom_vline(xintercept = 1,linetype="dashed") +
  facet_grid(rows = vars(var),scales = "free_y") +
  scale_color_manual(values=c("gray20","gray50")) +
  theme_minimal() +
  theme(legend.title = element_blank(),legend.position = "bottom") +
  labs(x="",y="")

ggsave("figd1.pdf",height=8,width=6)

#how many diffs are sig?
table(balanceplotdf$p.value<.05)

# E Regression tables ----

# manipulation checks
mcm_biv <- lm(sdimmpos~expcondition,data = acdf)
mcm_adj <- lm(sdimmpos~expcondition+education+occupation+partygroup15,data = acdf)

# SD ptv
sdptvm_biv <- lm(sdptv~expcondition,data=acdf)
sdptvm_adj <- lm(sdptv~expcondition+education+occupation+partygroup15,data=acdf)

#max left bloc ptv
maxlbptvm_biv <- lm(maxlbptv~expcondition,data=acdf)
maxlbptvm_adj <- lm(maxlbptv~expcondition+education+partygroup15,data=acdf)

# Table E1
regtabtxt <- texreg(list(mcm_biv,mcm_adj,sdptvm_biv,sdptvm_adj,maxlbptvm_biv,maxlbptvm_adj),
                    stars = c(.01,.05,.1),
                    omit.coef = "xxx",
                    custom.coef.names = c("Intercept","Accommodative treatment","Adversarial treatment",rep("xxx",18)),
                    booktabs = T,dcolumn = T,
                    label = "regtab",
                    caption = "Models of propensity to vote for Social Democrats",
                    caption.above = T,
                    fontsize = "footnotesize",
                    float.pos = "!hbp",
                    use.packages = F) %>% 
  str_split("\n") %>% 
  pluck(1) %>%
  .[c(1:15,52:63)]

regtabtxt[17] <- "Covariate adjustment&            & $\\checkmark$      &            & $\\checkmark$      &            & $\\checkmark$      \\\\"
regtabtxt[8] <- " & \\multicolumn{2}{c}{Perceived SD pos.} & \\multicolumn{2}{c}{SD PTV} & \\multicolumn{2}{c}{Left bloc vote int} \\\\"

write_lines(regtabtxt,"tabe1.tex")

#relevel party group variable
acdf$partygroup15 <- relevel(acdf$partygroup15,"Other/DK")

aiintm_biv <- lm(sdptv~antiimm*expcondition,data=acdf)
aiintm_adj <- lm(sdptv~antiimm*expcondition+gender+agegrp+education+partygroup15,data=acdf)

pgintm_biv <- lm(sdptv~expcondition*partygroup15,data=acdf)
pgintm_adj <- lm(sdptv~expcondition*partygroup15+gender+agegrp+education,data=acdf)

# Table E2
int1tab <- texreg(list(aiintm_biv,aiintm_adj,pgintm_biv,pgintm_adj),
                  stars = c(.01,.05,.1),
                  omit.coef = "xxx",
                  custom.coef.names = c("Intercept","Anti-immigration","Accommodative","Adversarial",
                                        "Anti-imm. x Accommodative","Anti-imm. x Adversarial",
                                        rep("xxx",11),
                                        "DPP","Left bloc","Other right",
                                        "DPP x Accommodative","DPP x Adversarial",
                                        "Left bloc x Accommodative","Left bloc x Adversarial",
                                        "Other right x Accommodative","Other right x Adversarial"),
                  booktabs = T,
                  dcolumn = T,
                  label = "int1tab",
                  caption = "Interaction models: Social Democrats PTV",
                  caption.above = T,
                  fontsize = "footnotesize",
                  float.pos = "!hbp",
                  use.packages = F) %>% 
  str_split("\n") %>% 
  .[[1]] %>% 
  .[c(1:21,44:73)]

int1tab[41] <- "Covariate adjustment&            & $\\checkmark$      &            & $\\checkmark$ \\\\"
int1tab[8] <- " & \\multicolumn{2}{c}{Moderator: anti-imm. att.} & \\multicolumn{2}{c}{Moderator: frmr. vote} \\\\"

write_lines(int1tab,"tabe2.tex")


aiintm_biv_lb <- lm(maxlbptv~antiimm*expcondition,data=acdf)
aiintm_adj_lb <- lm(maxlbptv~antiimm*expcondition+gender+agegrp+education+partygroup15,data=acdf)

pgintm_biv_lb <- lm(maxlbptv~expcondition*partygroup15,data=acdf)
pgintm_adj_lb <- lm(maxlbptv~expcondition*partygroup15+gender+agegrp+education,data=acdf)

# Table E3
int2tab <- texreg(list(aiintm_biv_lb,aiintm_adj_lb,pgintm_biv_lb,pgintm_adj_lb),
                  stars = c(.01,.05,.1),
                  omit.coef = "xxx",
                  custom.coef.names = c("Intercept","Anti-immigration","Accommodative","Adversarial",
                                        "Anti-imm. x Accommodative","Anti-imm. x Adversarial",
                                        rep("xxx",11),
                                        "DPP","Left bloc","Other right",
                                        "DPP x Accommodative","DPP x Adversarial",
                                        "Left bloc x Accommodative","Left bloc x Adversarial",
                                        "Other right x Accommodative","Other right x Adversarial"),
                  booktabs = T,dcolumn = T,
                  label = "int2tab",
                  caption = "Interaction models: Left bloc vote intention",
                  caption.above = T,
                  fontsize = "footnotesize",
                  float.pos = "!hbp",
                  use.packages = F) %>% 
  str_split("\n") %>% 
  .[[1]] %>% 
  .[c(1:21,44:73)]

int2tab[41] <- "Covariate adjustment&            & $\\checkmark$      &            & $\\checkmark$ \\\\"
int2tab[8] <- " & \\multicolumn{2}{c}{Moderator: anti-imm. att.} & \\multicolumn{2}{c}{Moderator: frmr. vote} \\\\"

write_lines(int2tab,"tabe3.tex")


# F Test of Linear interaction effect assumption ----

interflex <- inter.binning(data=as.data.frame(acdf),
                           Y="sdptv",
                           D="expcondition_refadv",
                           X="antiimm",
                           base="Adversarial",
                           na.rm=T)

plot(interflex,
     to.show = "Accommodative",
     theme.bw = T,
     main="Social Democrats propensity to vote",
     ylab = "Effect on PTV",
     xlab = "Anti-immigration attitude")

ggsave("figf1.pdf",width=7,height=5)

